#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Created by liaoyangyang1 on 2019/9/9 上午11:45.
"""
from flask import Flask, render_template, request, jsonify
import os
import xlrd

app = Flask(__name__)

HOST = '127.0.0.1'
PORT = 10101

# 指定网页找静态文件的路径
app.add_template_global('http://{0}:{1}/static'.format(HOST, PORT), 'STATIC_URL')
# 网站名称
app.add_template_global('excel变在线报表', 'PROJECTNAME')
# 项目路径
base_dir = os.path.dirname(os.path.abspath(__file__))
# 存放excel的路径
excel_dir = os.path.join(base_dir, 'excel')


@app.route('/showpage/<filename>')
def show_page(filename):
    """
    excel显示的详情页
    :param filename:文件名
    :return:
    """
    # 获取侧边栏的列表
    sidebars = get_sidebars()
    if filename in sidebars:
        # 每个excel的路径
        file_dir = os.path.join(excel_dir, filename)
        # excel的内容
        table_list = read_excel(file_dir)
        # 渲染到excel.html这个页面上
        return layout('excel.html', table_list=table_list, filename=filename)
    else:
        return '没有这个文件'


@app.route('/')
def index():
    """
    首页看这里
    :return:
    """
    return layout('index.html')


@app.route('/upload_excel', methods=['POST'])
def upload_excel():
    """
    怎么接收一个或多个上传的附件
    :return:
    """
    files = request.files.getlist('file[]')
    if files and len(files) > 0:
        for file in files:
            if check_upload_filetype(file.filename):
                local_dir = os.path.join(excel_dir, file.filename)
                file.save(local_dir)
    return 'success'


def check_upload_filetype(filename):
    """
    检查上传文件是不是excel
    :param filename: 文件名
    :return:
    """
    if filename and '.' in filename:
        if filename.split('.')[-1] == 'xls' or filename.split('.')[-1] == 'xlsx':
            return True
        else:
            return False
    else:
        return False


def read_excel(filename):
    """
    读取excel的内容
    :param filename: 文件名
    :return:
    """
    data = xlrd.open_workbook(filename)
    tables = data.sheet_names()
    table_list = []
    for id in tables:
        sheet_dict = {}
        table = data.sheet_by_name(id)
        table_name = table.name
        table_sheet_title = table.row_values(0)
        table_sheet_values = []
        for i in range(1, table.nrows):
            if not (table.row_values(i) == [''] * table.ncols):
                table_sheet_values.append(table.row_values(i))
        sheet_dict['table_name'] = table_name
        sheet_dict['table_sheet_title'] = table_sheet_title
        sheet_dict['table_sheet_values'] = table_sheet_values
        table_list.append(sheet_dict)
    return table_list


def get_sidebars():
    """
    获取侧边栏信息，也就是所有excel文件名
    :return:
    """
    sidebars = []
    for filename in os.listdir(excel_dir):
        sidebars.append(filename)

    return sidebars


def layout(template_name_or_list, **context):
    """
    渲染页面用的，直接用就行了
    :param template_name_or_list: html页面名称
    :param context: 变量
    :return:
    """
    sidebars = get_sidebars()
    return render_template(template_name_or_list,
                           sidebars=sidebars,
                           **context)


if __name__ == '__main__':
    app.run(host=HOST, port=PORT, debug=True)
